package com.tjsoft.demo.student.dao;

import java.util.List;

import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.tjsoft.demo.student.model.Student;

public class StudentDAO extends HibernateDaoSupport {

	public static final String NAME = "name";
	public static final String PASSWORD = "password";
	public static final String SEX = "sex";
	public static final String AGE = "age";
	
	public void save(Student entity){
		try{
			getHibernateTemplate().save(entity);
		}catch(RuntimeException e){
			throw e;
		}
	}
	
	public void update(Student entity){
		try{
			getHibernateTemplate().update(entity);
		}catch(RuntimeException e){
			throw e;
		}
	}
	
	public void delete(Student entity){
		try{
			getHibernateTemplate().delete(entity);
		}catch(RuntimeException e){
			throw e;
		}
	}
	
	public Student findById(Long sid) {
		try {
			Student entity = (Student) getHibernateTemplate().get(
					"com.tjsoft.demo.student.model.Student", sid);
			return entity;
		} catch (RuntimeException re) {
			throw re;
		}
	}
	
	public List findAll(){
		try{
			List list = getHibernateTemplate().find("from Student");
			return list;
		}catch(RuntimeException e){
			throw e;
		}
	}
	
	public List findList(String hql, Object... values) {
		Query query = createQuery(hql, values);
		return query.list();
	}
	
	/**
	 * 创建一个查询对象。
	 * 
	 * @param hql
	 *            HQL语句
	 * @param values
	 *            参数值
	 * @return 返回一个查询对象。
	 */
	public Query createQuery(String hql, Object... values) {
		Query query = getSession().createQuery(hql);
		for (int i = 0; i < values.length; i++) {
			query.setParameter(i, values[i]);
		}
		return query;
	}
	
}
